package com.situ.web.filter;
import com.situ.web.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "login",urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LoginFilter.init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("LoginFilter.doFilter");
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        String method = req.getParameter("method");
        String servletPath = req.getServletPath();

//        int lastIndex = servletPath.lastIndexOf(".");
//        String extension = servletPath.substring(lastIndex);

        //去完成登录，不需要继续验证
        if(servletPath.equals("/login.jsp")
            ||servletPath.equals("/user")&&method.equals("login")
            ||servletPath.equals("/fail.jsp")
            ||servletPath.equals("/code")
            ||servletPath.endsWith(".js")
            ||servletPath.endsWith(".css")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        HttpSession session = req.getSession();
        User user = (User)session.getAttribute("user");
        if(user == null){
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("LoginFilter.destroy");
    }
}
